# ai_sop_system/data_collector.py
import json
import time
from datetime import datetime
from typing import Dict, List, Any
from enum import Enum


class DataType(Enum):
    BEHAVIOR = "behavior"  # 用户行为数据
    PREFERENCE = "preference"  # 用户偏好数据
    CONTEXT = "context"  # 上下文环境数据
    FEEDBACK = "feedback"  # 用户反馈数据


class UserDataCollector:
    """AI助手用户数据采集模块"""

    def __init__(self):
        self.collected_data = []
        self.data_batch = []
        self.batch_size = 100

    def collect_user_data(self) -> Dict[str, Any]:
        """采集用户数据"""
        print("🔍 AI助手开始采集用户数据...")

        user_data = {
            "timestamp": datetime.now().isoformat(),
            "session_id": self._generate_session_id(),
            "data_types": {},
            "metadata": {}
        }

        # 采集多种类型数据
        user_data["data_types"][DataType.BEHAVIOR.value] = self._collect_behavior_data()
        user_data["data_types"][DataType.PREFERENCE.value] = self._collect_preference_data()
        user_data["data_types"][DataType.CONTEXT.value] = self._collect_context_data()
        user_data["data_types"][DataType.FEEDBACK.value] = self._collect_feedback_data()

        # 元数据
        user_data["metadata"] = {
            "data_quality_score": self._calculate_data_quality(user_data),
            "collection_duration": time.time(),
            "source": "ai_assistant"
        }

        self.collected_data.append(user_data)
        self.data_batch.append(user_data)

        # 批量处理
        if len(self.data_batch) >= self.batch_size:
            self._process_batch_data()

        print(f"✅ 用户数据采集完成，共采集 {len(user_data['data_types'])} 种数据类型")
        return user_data

    def _collect_behavior_data(self) -> Dict[str, Any]:
        """采集用户行为数据"""
        return {
            "interaction_patterns": {
                "click_sequence": ["home", "search", "product", "cart"],
                "time_spent_per_page": {"home": 45.2, "product": 120.5, "cart": 30.1},
                "common_actions": ["search", "filter", "compare", "purchase"]
            },
            "usage_frequency": {
                "daily_logins": 3,
                "weekly_activity": 15,
                "feature_usage": {"chat": 8, "search": 12, "help": 2}
            },
            "navigation_flow": {
                "entry_points": ["direct", "search_engine", "social_media"],
                "exit_pages": ["checkout", "product_page", "home"],
                "conversion_paths": [
                    {"path": "search→product→cart→checkout", "success_rate": 0.15},
                    {"path": "home→category→product→cart", "success_rate": 0.08}
                ]
            }
        }

    def _collect_preference_data(self) -> Dict[str, Any]:
        """采集用户偏好数据"""
        return {
            "content_preferences": {
                "preferred_categories": ["technology", "education", "business"],
                "content_format": ["video", "article", "interactive"],
                "difficulty_level": "intermediate"
            },
            "interaction_preferences": {
                "communication_style": "detailed",  # brief, detailed, technical
                "response_speed": "balanced",  # instant, balanced, delayed
                "notification_preferences": ["email", "push", "in_app"]
            },
            "learning_style": {
                "prefers_visual": True,
                "prefers_hands_on": False,
                "prefers_theoretical": True,
                "pace_preference": "self_paced"  # guided, self_paced, intensive
            }
        }

    def _collect_context_data(self) -> Dict[str, Any]:
        """采集上下文环境数据"""
        return {
            "device_context": {
                "device_type": "mobile",  # desktop, mobile, tablet
                "operating_system": "iOS",
                "browser": "Safari",
                "screen_resolution": "1125x2436"
            },
            "environment_context": {
                "location": "office",  # home, office, travel
                "network_quality": "good",
                "time_of_day": "afternoon",
                "day_of_week": "weekday"
            },
            "task_context": {
                "current_task": "research",
                "task_complexity": "medium",
                "time_available": "limited",  # ample, limited, urgent
                "goal_type": "learning"  # entertainment, learning, problem_solving
            }
        }

    def _collect_feedback_data(self) -> Dict[str, Any]:
        """采集用户反馈数据"""
        return {
            "explicit_feedback": {
                "ratings": {
                    "content_quality": 4.5,
                    "response_relevance": 4.2,
                    "ease_of_use": 4.8
                },
                "direct_feedback": "帮助很大，但响应可以更快一些",
                "suggestions": ["增加更多实例", "提供进度跟踪"]
            },
            "implicit_feedback": {
                "completion_rates": {
                    "task_completion": 0.85,
                    "content_consumption": 0.92,
                    "goal_achievement": 0.78
                },
                "engagement_metrics": {
                    "return_rate": 0.75,
                    "session_duration": 420,
                    "interaction_depth": 8.5
                }
            },
            "sentiment_analysis": {
                "overall_sentiment": "positive",
                "emotion_scores": {"satisfaction": 0.8, "frustration": 0.1, "confusion": 0.2},
                "key_phrases": ["很有帮助", "响应及时", "界面友好"]
            }
        }

    def _calculate_data_quality(self, user_data: Dict) -> float:
        """计算数据质量分数"""
        completeness_score = self._check_completeness(user_data)
        consistency_score = self._check_consistency(user_data)
        freshness_score = self._check_freshness(user_data)

        return (completeness_score + consistency_score + freshness_score) / 3

    def _check_completeness(self, user_data: Dict) -> float:
        """检查数据完整性"""
        required_fields = ["behavior", "preference", "context", "feedback"]
        present_fields = [field for field in required_fields if field in user_data.get("data_types", {})]
        return len(present_fields) / len(required_fields)

    def _check_consistency(self, user_data: Dict) -> float:
        """检查数据一致性"""
        # 简化的一致性检查
        try:
            behavior_data = user_data["data_types"]["behavior"]
            preference_data = user_data["data_types"]["preference"]

            # 检查行为与偏好是否一致
            if (behavior_data["usage_frequency"]["daily_logins"] > 5 and
                    preference_data["interaction_preferences"]["response_speed"] == "instant"):
                return 0.9
            return 0.7
        except:
            return 0.5

    def _check_freshness(self, user_data: Dict) -> float:
        """检查数据新鲜度"""
        # 假设所有数据都是实时采集的
        return 1.0

    def _generate_session_id(self) -> str:
        """生成会话ID"""
        return f"SESSION_{datetime.now().strftime('%Y%m%d_%H%M%S')}_{hash(str(time.time()))}"

    def _process_batch_data(self):
        """处理批量数据"""
        if self.data_batch:
            print(f"🔄 处理批量数据，共 {len(self.data_batch)} 条记录")
            # 这里可以添加批量处理逻辑，如数据压缩、加密等
            self.data_batch.clear()

    def get_collection_stats(self) -> Dict[str, Any]:
        """获取采集统计信息"""
        return {
            "total_sessions": len(self.collected_data),
            "data_types_collected": [dt.value for dt in DataType],
            "average_quality_score": sum(
                data["metadata"]["data_quality_score"]
                for data in self.collected_data
            ) / len(self.collected_data) if self.collected_data else 0,
            "last_collection_time": self.collected_data[-1]["timestamp"] if self.collected_data else None
        }